<?php


namespace app\index\controller;

use think\Controller;
use app\common\services\ConfirmReceipt;

class Timing extends Controller
{
    //  自动确认收货后，变更金额
    public function index()
    {
        $time = date("Y-m-d H:i:s", strtotime("-7 day"));
        $send = model('order')
            ->where('or_status', 2)
            ->whereTime('deliver_time', '<=', $time)
            ->column('id');
         //订单更新
        $update = db('order')->whereIn('id', $send)->update(['or_status' => 3]);
        if ($update) {
            $file = 'timingLog.txt';
            $datetime = date("Y-m-d H:i:s");
            $string = implode(',', $send);
            $date = "自动收货成功、收货订单ID为:$string 时间:$datetime";
            file_put_contents($file, $date . PHP_EOL, FILE_APPEND);
        }

        // 确认收货后发送各种奖励
        if (!empty($send)) {
            // 金额重新调整
            $tz = new ConfirmReceipt();
            // 符合时间订单id
            $tz->index($send);
        }
    }

    // 一百家店主自动升级运营中心
    public function remove()
    {
        $time = date('Y-m-d H:i:s');
        $us_type =  model('user')->where('us_type',2)->column('id');
//        halt($us_type);
        foreach ($us_type as $k=>$v){
            // 查询直推店主个数
            $dianNum = model('user')->where('us_pid',$v)->where('us_type',2)->count();

            if ($dianNum >=1)
            {
                // 获取该用户的所有下级，用于计算分离前业绩
                $pid = model('User')->where('id',$v)->value('us_pid'); // 用户原上级

                $teams =  $this->getAllChildrenId($v);
                array_unshift ($teams,$v);

                $teamMoney = model('MoneyDetailed')
                    ->whereIn('us_id',$teams)->sum('money');

                // 团队独立出来
                model('User')->where('id',$v)
                    ->update(['yun_yuan_pid'=>$pid,'yun_yuan_yeji'=>$teamMoney,'us_pid'=>0,'cheng_yun_time'=>$time]);

                // 确认修改会员身份
                model('User')::update(['us_type' => 3], ['id' => $v]);
            }
        }
    }

    public function getAllChildrenId($id)
    {
        $ids = $this->getChildrenId($id) ?? [];
        $noHandleIds = $ids;
        while (!empty($noHandleIds)) {
            $id = array_shift($noHandleIds);
            $childrenIds = $this->getChildrenId($id);
            foreach ($childrenIds as $v) {
                array_push($ids, $v);
                array_push($noHandleIds, $v);
            }
        }
        return $ids;
    }

    public function getChildrenId($id)
    {
        return db('user')
            ->where('us_pid', $id)
            ->column("id");
    }

}